﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using cpe.cpein.UI.UserCpeInServiceReference;
using Gs = cpe.cpein.UI.GroupCpeInServiceReference;

namespace cpe.cpein.UI.Controls
{
    /// <summary>
    /// Interaction logic for UCListGroups.xaml
    /// </summary>
    public partial class UCListGroups : UserControl
    {
        #region Variables

        /// <summary>
        /// Groups of the control.
        /// </summary>
        private List<Group> _groups = new List<Group>();
        public List<Group> MyGroups
        { 
            get { return _groups; } 
            set { _groups = value; } 
        }

        /// <summary>
        /// Group Types
        /// </summary>
        private List<Gs.GroupType> _groupTypes = new List<Gs.GroupType>();
        public List<Gs.GroupType> MyGroupTypes
        {
            get { return _groupTypes; }
            set { _groupTypes = value; }
        }

        /// <summary>
        /// Current user.
        /// </summary>
        User _currentUser;

        /// <summary>
        /// Current Main window
        /// </summary>
        FMainWindow _WinParent;

        /// <summary>
        /// Adding group User Control 
        /// </summary>
        UCAddGroup _ucGroupToAdd;

        #endregion

        #region Create and Open

        /// <summary>
        /// Default constructor.
        /// </summary>
        public UCListGroups()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public UCListGroups(User current, FMainWindow WinParent)
        {
            InitializeComponent();
            this._currentUser = current;
            this._WinParent = WinParent;
        }

        /// <summary>
        /// Function fires when the UC is Loaded.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.MyGroups = new List<Group>();
            InitializeLists();
        }

        #endregion

        #region Event Methods

        /// <summary>
        /// Function fires when a double=click is fired on the grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GroupGrid_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (GroupGrid.SelectedValue != null)
            {
                OpenGroupDetails(int.Parse(GroupGrid.SelectedValue.ToString()));
            }
        }

        /// <summary>
        /// Function fires when Refresh button is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btRefresh_Click(object sender, RoutedEventArgs e)
        {
            FindGroups();
        }

        /// <summary>
        /// Fires when the button Nouveau is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btNew_Click(object sender, RoutedEventArgs e)
        {
            if (_ucGroupToAdd == null)
                _ucGroupToAdd = new UCAddGroup(_currentUser,_WinParent);
            LoadUserControl(_ucGroupToAdd);
        }

        #endregion

        #region Methods

        /// <summary>
        /// Function which allows to open the group details
        /// </summary>
        /// <param name="p"></param>
        private void OpenGroupDetails(int p)
        {
            using (UsersServiceClient us = new UsersServiceClient())
            {
                Group group = us.GetGroupByID(p, this._currentUser);
                LoadUserControl(new UCGroup(this._currentUser, group, this._WinParent));
            }
        }

        /// <summary>
        /// Function which allows to initialize the Lists.
        /// </summary>
        private void InitializeLists()
        {
            Tools.Tools.BeginWaitStatus();
            ThreadPool.QueueUserWorkItem(delegate {
                List<Group> grps = GetGroups(false);
                List<Gs.GroupType> grt = GetGroupTypes();
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.MyGroups.Clear();
                    this.MyGroups.AddRange(grps);
                    this.GroupGrid.ItemsSource = grps;

                    this.MyGroupTypes.Clear();
                    this.MyGroupTypes.AddRange(grt);
                    this.cmbType.ItemsSource = grt;

                    Tools.Tools.EndWaitStatus();
                }));
            });
        }

        /// <summary>
        /// Function used to Find Groupes
        /// </summary>
        private void FindGroups()
        {
            bool searchInFriends = (chkRelation.IsChecked == true);
            Tools.Tools.BeginWaitStatus();
            ThreadPool.QueueUserWorkItem(delegate
            {
                List<Group> grps = GetGroups(searchInFriends);
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.MyGroups.Clear();
                    this.MyGroups.AddRange(grps);
                    FilterGroups();
                    this.GroupGrid.ItemsSource = MyGroups;

                    Tools.Tools.EndWaitStatus();
                }));
            });
        }

        /// <summary>
        /// Function which allows to filter groups in the grid.
        /// </summary>
        private void FilterGroups()
        {
            if (this.cmbType.SelectedValue != null && !String.IsNullOrEmpty(this.cmbType.SelectedValue.ToString()))
            {
                var req = from Group in MyGroups
                          where Group.IDType == int.Parse(this.cmbType.SelectedValue.ToString())
                          select Group;
                MyGroups = req.ToList();
            }
            if (!String.IsNullOrEmpty(this.txtName.Text))
            {
                var req = from Group in MyGroups
                          where Group.Label.ToLower().IndexOf(this.txtName.Text.ToLower()) >= 0
                          select Group;
                MyGroups = req.ToList();
            }
        }

        /// <summary>
        /// Function used to get the groups.
        /// </summary>
        private List<Group> GetGroups(bool searchInFriends)
        {
            using(UsersServiceClient us = new UsersServiceClient())
            {
                List<Group> grps = null;
                if (searchInFriends)
                    grps = new List<Group>(us.GetGroups(this._currentUser, this._currentUser));
                else
                    grps = new List<Group>(us.GetAllGroups(false, this._currentUser));
                return grps;
            }
        }

        /// <summary>
        /// Function used to get the group types.
        /// </summary>
        private List<Gs.GroupType> GetGroupTypes()
        {
            using (Gs.GroupsServiceClient gs = new Gs.GroupsServiceClient())
            {
                return new List<Gs.GroupType>(gs.GetAllGroupTypes(
                    new Gs.User()
                    {
                        Email = this._currentUser.Email,
                        Id = this._currentUser.Id,
                        IDAddress = this._currentUser.IDAddress,
                        IsDeleted = this._currentUser.IsDeleted,
                        Lastname = this._currentUser.Lastname,
                        Name = this._currentUser.Name,
                    }));
            }
        }

        /// <summary>
        /// Function which allows to load a UserControl in the form.
        /// </summary>
        /// <param name="uc"></param>
        private void LoadUserControl(UserControl uc)
        {
            _WinParent.ucContent.Content = uc;
        }
        #endregion
    }
}
